package com.studyspace.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.studyspace.entity.User;
import com.studyspace.entity.UserRole;
import com.studyspace.mapper.UserMapper;
import com.studyspace.model.LoginModel;
import com.studyspace.model.RegisterModel;
import com.studyspace.result.Result;
import com.studyspace.service.UserRoleService;
import com.studyspace.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyspace.utils.UniqueIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ljl
 * @since 2021-11-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public User register(RegisterModel registerModel, HttpServletRequest httpServletRequest) {

        String phone = registerModel.getPhone();
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));
        if (null != user) {
            return null;
        }

        User newOne = new User();

        newOne.setUsername(registerModel.getUsername());//设置用户名
        newOne.setUid(UniqueIdUtil.getUniqueId());//设置用户id
        newOne.setRoleId(1l);//设置用户角色
        newOne.setPhone(registerModel.getPhone());

        String password = registerModel.getPassword();
        String encodePassword = new BCryptPasswordEncoder().encode(password);
        newOne.setPassword(encodePassword);

        return newOne;
    }

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username", name));
        if (null == user) {
            throw new UsernameNotFoundException("用户未注册!");
        }

        Collection<GrantedAuthority> authorities = getAuthorities(user);

        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                new BCryptPasswordEncoder().encode(user.getPassword()), authorities);
    }

    // 获取角色信息
    private Collection<GrantedAuthority> getAuthorities(User user){
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        UserRole role = userRoleService.getById(user.getRoleId());
        //注意：这里每个权限前面都要加ROLE_。否在最后验证不会通过
        authList.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));

        return authList;
    }
}
